package cn.kgc.controller;

import cn.kgc.pojo.Branch;
import cn.kgc.pojo.Resume;
import cn.kgc.pojo.position;
import cn.kgc.service.resumeService;
import cn.kgc.service.userService;
import cn.kgc.until.UploadUntils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: 申乾航
 * @date: 2022/2/3
 * @description:
 */
@RequestMapping("/resume")
@Controller

public class resumeController {


    Logger logger=Logger.getLogger(resumeController.class);
    @Resource
    private resumeService resumeService;

    @Resource
    private userService userServices;



    /*@RequestMapping("/indexs")
    public String index(){
      return "index";
    }*/

    @RequestMapping("/h4")
    public String getList(){
        return "shenguanli";
    }

    @RequestMapping("/aLists")
    @ResponseBody
    public String getAList(@RequestParam Integer currentPage,
                           @RequestParam Integer pageSize,@RequestParam String reName1,@RequestParam String posname
            ,@RequestParam String workEx,@RequestParam String resState,@RequestParam String checkTime){
        PageHelper.startPage(currentPage,pageSize);
        Page<Resume> lists = resumeService.getList(reName1,posname,workEx,resState,checkTime);
        PageInfo<Resume> pageInfos = new PageInfo<Resume>(lists);

        return  JSONObject.toJSONStringWithDateFormat(pageInfos,"yyyy-MM-dd");
    }
    @RequestMapping("/dengji")
    public String getDengji(Model model){
       // User ming = resumeService.ming(userCode, userPwd);
        //model.addAttribute("mings",ming.getUserName());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        model.addAttribute("shijian",sdf.format(date));

        return "shendengji";
    }
//,@RequestParam("userCode") String userCode, @RequestParam("userPassword") String userPwd
    /*@RequestMapping("/ming")
    public String ming(Model model,){

        return "shendengji";
    }*/


    @RequestMapping("tiao")
    public String tiao(){

        return "shentiao";
    }

    /**
     * 查询职位名称.	职位编码，。所属部门:
     * 组织分页
     * @return
     */

    @RequestMapping("/zuzhi")
    @ResponseBody
    public String zuzhifenye(@RequestParam Integer currentPage,
                             @RequestParam Integer pageSize,@RequestParam String posName,
                             @RequestParam String posCode,
                             @RequestParam String brName){

        PageHelper.startPage(currentPage,pageSize);
        Page<position> branchList = resumeService.getBranchList(posName,posCode,brName);
        PageInfo<position> positionPageInfo = new PageInfo<>(branchList);

        return JSONObject.toJSONStringWithDateFormat(positionPageInfo,"yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 下拉框
     * @return
     */
    @RequestMapping("/zuzhiye")
    @ResponseBody
    public String zuzhiye(){

        List<Branch> branches = resumeService.XiaLaKuangBranch();

        return JSONObject.toJSONString(branches);
    }

    /**
     *
     * 渲染职位名称，职位分类，职位编码
     * @param id
     * @return
     */
    @RequestMapping("/zhiyefen")
    @ResponseBody
    public String zhiye(@RequestParam Integer id){
        position positionFen = resumeService.getPositionFen(id);
        return JSONObject.toJSONString(positionFen);
    }



    //SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    @RequestMapping("/tianjia_shen")
    @ResponseBody
    public boolean tianjia_shen(@RequestParam ("posCode") String posCode, Resume resume,
         @RequestParam("file") MultipartFile affix
        ) throws IOException {
        //获得文件的名称
        String filename=affix.getOriginalFilename();

        System.out.println("+++++============="+filename);
       /* int point = filename.lastIndexOf(".");//得到.前面的file的字符长度
        ++point;
        System.out.println("-------------------"+point);
        String types = filename.substring(point);
        System.out.println("----------==========---------"+types);*/

        String suf = FilenameUtils.getExtension(filename);
        //System.out.println(suf+"22222222222222222");

        if(suf.equalsIgnoreCase("doc")|| suf.equalsIgnoreCase("pdf") || suf.equalsIgnoreCase("docx")){

            //首先调用我们写的工具类
            String upload = UploadUntils.upload(affix);//获得了一个文件路径

            resume.setAffix(upload);
            Integer postions = resumeService.selId(posCode);
            resume.setPosId(postions);
            boolean tianjia = resumeService.tianjia(resume);
            if(tianjia){
                System.out.println("成功");

            }else {
                System.out.println("失败");
            }
            System.out.println("添加成功！");
            return tianjia;
        }else{
            System.out.println("添加失败！！！");
           // response.getWriter().print("<script>alert('格式不正确，请输入正确的格式');window.location.href='shendengji.html';</script>");
            return  false;
        }
    }

    @RequestMapping("/xiugaicha/{id}")

    public String getLists(@PathVariable("id") Integer id, HttpSession session,
              HttpServletRequest request, Model model){
        Resume resume = resumeService.xiugai_cha(id);
         model.addAttribute("cha11",resume);
        return "shenxiugai";

    }


    @RequestMapping("/xiugai_shen")
    @ResponseBody
    public boolean xiugai_shen(@RequestParam ("posCode") String posCode, Resume resume,
                              @RequestParam("file") MultipartFile affix, HttpServletResponse response) throws IOException {

        //获得文件的名称
        String filename = affix.getOriginalFilename();

        System.out.println("+++++=============" + filename);

        String suf = FilenameUtils.getExtension(filename);

        if (suf.equalsIgnoreCase("doc") || suf.equalsIgnoreCase("pdf") || suf.equalsIgnoreCase("docx")) {
            //首先调用我们写的工具类
            String upload = UploadUntils.upload(affix);//获得了一个文件路径

            resume.setAffix(upload);
            Integer postions = resumeService.selId(posCode);
            resume.setPosId(postions);
            boolean b = resumeService.xiugai_shen(resume);
            if (b) {
                System.out.println("修改成功");
            } else {
                System.out.println("修改失败");
            }
            return b;

        }else{
            System.out.println("修改失败！！！");
            return  false;
        }

    }


    @RequestMapping("/chakantiaos/{id}")
    public String chakantiao(@PathVariable("id") Integer id, Model model){
        //position positionFen = resumeService.getPositionFen(id);

        Resume resume = resumeService.chakan(id);

        model.addAttribute("cha33",resume);
        //model.addAttribute("cha22",positionFen);
        return "shenchakan";
    }



    @GetMapping("/dowmload")
    public void download(String openStyle,@RequestParam("id") Integer id, HttpServletResponse response) throws IOException {
        openStyle = openStyle == null ? "attachment" : openStyle;

        Resume resume = resumeService.chakan(id);
        // 获取文件路径
        System.out.println("File: ---------------------" + resume);
       // String property = System.getProperty("user.dir")+"\\src\\main\\resources\\upload\\"+resume.getAffix();
      //  System.out.println(property);
        String paths=resume.getAffix();
        // 获取文件输入流（把磁盘上的文件通过IO加载到程序（内存）中
        FileInputStream fis = new FileInputStream(new File(paths));
        System.out.println("=================================="+fis);
        // 附件下载
        // 注意：为防止中文乱码，需要使用UTF-8
        response.setHeader("content-disposition", "inline;fileName=" + URLEncoder.encode(resume.getAffix(), "UTF-8"));

        // 获取响应流（找到后需要通过Response发送回给用户
        ServletOutputStream os = response.getOutputStream();
        // 文件拷贝
        IOUtils.copy(fis, os);
        // 关闭流
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);

    }



    //删除
    @RequestMapping("/shanchu")
    @ResponseBody
    public String shanchu(@RequestParam("id") Integer id, @RequestParam("resState")String resState){
        int shanchu = resumeService.shanchu(id, resState);

        if (shanchu>0){
            System.out.println("删除了"+shanchu);
        }

        return JSONObject.toJSONString(shanchu);
    }


    //弹层修改
    @RequestMapping("/xuigai_03")
    @ResponseBody
    public String xiugai_03(@RequestParam("referrer")String referrer,@RequestParam("recommendTime")String recommendTime,
                            @RequestParam("opinion")String opinion,@RequestParam("id")Integer id){
        int i = resumeService.xiugai_03(referrer, recommendTime, opinion, id);

        if (i>0){
            System.out.println("修改了"+i);
        }
        return JSONObject.toJSONString(i);
    }



}
